package com.zyl.pts.service.serviceImpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyl.pts.config.enums.CodeAndMessageEnum;
import com.zyl.pts.config.exception.ServiceException;
import com.zyl.pts.domain.bean.Animal;
import com.zyl.pts.domain.dto.AnimalDTO.AnimalUpdateOrAddDTO;
import com.zyl.pts.domain.vo.AnimalVO.BaseInfoAnimalPageVO;
import com.zyl.pts.domain.vo.AnimalVO.BaseInfoAnimalVO;
import com.zyl.pts.mapper.AnimalMapper;
import com.zyl.pts.mapper.MQMapper;
import com.zyl.pts.service.AnimalService;
import com.zyl.pts.service.HurdlesService;
import com.zyl.pts.utils.CUtil;
import com.zyl.pts.utils.OssUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * @version v1.0
 * @ProjectName: product_source
 * @Package: com.zyl.pts.service.serviceImpl
 * @ClassName: AnimalServiceImpl
 * @Description TODO()
 * @Author 翟玉龙
 * @Date 2024/11/20-8:45
 */
@Service
public class AnimalServiceImpl implements AnimalService {
    private static final String SOURCE_PATH = "http://localhost:9527/#/source/";

    private final AnimalMapper animalMapper;
    private final HurdlesService hurdlesService;
    private final MQMapper mqMapper;

    private final OssUtil ossUtil;

    public AnimalServiceImpl(
            AnimalMapper animalMapper,
            OssUtil ossUtil,
            HurdlesService hurdlesService,
            MQMapper mqMapper
    ) {
        this.animalMapper = animalMapper;
        this.ossUtil = ossUtil;
        this.hurdlesService = hurdlesService;
        this.mqMapper = mqMapper;
    }

    /**
     * 根据动物编号生成二维码
     * @param animalId 动物编号
     * @return {@link CodeAndMessageEnum }
     */
    @Transactional
    @Override
    public CodeAndMessageEnum generateQRCode(String animalId) {
        String ImgUrl = "";
        try {
            String content = SOURCE_PATH + animalId;
            File file = CUtil.generateQRCode(content, 500, 500, CUtil.UUID() + ".png");
            /*
                使用MockMultipartFile将File转换为MultipartFile
             */
            MultipartFile converted = CUtil.convertMultipartFile(file);
            ImgUrl = ossUtil.uploadOss(converted);
        } catch (Exception e) {
            CUtil.logError("文件上传失败: " + e.getMessage());
        }
        /*
            判断是否已经存在该动物编号的二维码
         */
        if(mqMapper.queryQRCodeByAnimalId(animalId) == 1) { // 修改
            return mqMapper.updateAnimalQRCode(animalId, ImgUrl) == 1 ?
                    CodeAndMessageEnum.SUCCESS_GENERATE_QRCODE : CodeAndMessageEnum.ERROR_QRCODE_GENERATE;
        }
        // 新增
        return mqMapper.insertAnimalQRCode(animalId, ImgUrl) == 1 ?
                CodeAndMessageEnum.SUCCESS_GENERATE_QRCODE : CodeAndMessageEnum.ERROR_QRCODE_GENERATE;
    }

    /**
     * 根据动物编号查询动物基本信息
     * @param animalId 动物编号
     * @return {@link BaseInfoAnimalVO }
     */
    @Override
    public BaseInfoAnimalVO queryAnimalInfoById(String animalId) {
        return animalMapper.queryAnimalInfoById(animalId);
    }

    /**
     * 分页并根据条件查询动物基本信息以及对应批次和栏圈
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param aHealthy 健康状况
     * @param aGender 性别
     * @return {@link PageInfo }<{@link BaseInfoAnimalPageVO }>
     */
    @Override
    public PageInfo<BaseInfoAnimalPageVO> queryAnimalInfoPage(Integer pageNum, Integer pageSize, String aHealthy, String aGender) {
        Page<BaseInfoAnimalPageVO> page = PageHelper.startPage(pageNum, pageSize);
        List<BaseInfoAnimalPageVO> pageVOS = animalMapper.queryAnimalInfoByPage(aHealthy, aGender);
        PageInfo<BaseInfoAnimalPageVO> pageInfo = new PageInfo<>(pageVOS);
        page.close();
        return pageInfo;
    }

    /**
     * 更新或者新增动物
     * @param animalUpdateOrAddDTO 动物信息
     * @return {@link CodeAndMessageEnum }
     */
    @Transactional
    @Override
    public CodeAndMessageEnum updateOrInsertAnimal(AnimalUpdateOrAddDTO animalUpdateOrAddDTO) {
        /*
            获取编号id
         */
        String animalId = animalUpdateOrAddDTO.getAAnimalId();
        /*
            获取栏舍id
         */
        String hurdlesId = animalUpdateOrAddDTO.getAHurdlesId();
        if (animalId == null) {
            animalUpdateOrAddDTO.setAAnimalId(CUtil.UUID());
            if(animalMapper.insertAnimal(animalUpdateOrAddDTO) == 1) {
                hurdlesService.changeSaved(hurdlesId, 1);
                return CodeAndMessageEnum.INSERT_SUCCESS;
            }
            return CodeAndMessageEnum.ERROR_INSERT;
        }
        /*
            如果是更新，根据ID查找原先的动物信息
            比对栏舍数据是否变动，如果变动，需要对栏舍表联动
         */
        String lessId = animalMapper.queryHurdlesId(animalId);
        if(!animalUpdateOrAddDTO.getAHurdlesId().equals(lessId) && lessId != null) {
            hurdlesService.changeSaved(lessId, -1);
            hurdlesService.changeSaved(animalUpdateOrAddDTO.getAHurdlesId(), 1);
        }
        return animalMapper.updateAnimal(animalUpdateOrAddDTO) == 1?
                    CodeAndMessageEnum.UPDATE_SUCCESS : CodeAndMessageEnum.ERROR_UPDATE;
    }

    /**
     * 根据动物编号删除动物
     * @param animalId 动物编号
     * @return {@link CodeAndMessageEnum }
     */
    @Transactional
    @Override
    public CodeAndMessageEnum deleteAnimalById(String animalId) {
        Animal animal = animalMapper.queryById(animalId);
        if(animal == null) {
            throw new ServiceException(String.format("该动物不存在：%s", animalId));
        }
        String hurdlesId = animal.getAHurdlesId();
        if(animalMapper.deleteAnimalById(animalId) == 1) {
            hurdlesService.changeSaved(hurdlesId, -1); // 修改栏舍
            mqMapper.deleteAnimalQRCode(animalId); // 删除二维码
            return CodeAndMessageEnum.DELETE_SUCCESS;
        }
        return CodeAndMessageEnum.ERROR_NOT_EXIST;
    }

    /**
     * 根据动物编号列表删除动物
     * @param animalIdList 动物编号列表
     * @return {@link CodeAndMessageEnum }
     */
    @Transactional
    @Override
    public CodeAndMessageEnum deleteAnimalByIdList(List<String> animalIdList) {
        List<Animal> lists = animalMapper.queryAnimalInfoByIdList(animalIdList);
        if(lists.size() != animalIdList.size()) {
            throw new ServiceException("部分动物不存在");
        }
        if(animalMapper.deleteAnimalByIds(animalIdList) == lists.size()) {
            for (Animal animal : lists) {
                hurdlesService.changeSaved(animal.getAHurdlesId(), -1); // 修改栏舍
                mqMapper.deleteAnimalQRCode(animal.getAAnimalId()); // 删除二维码
            }
            return CodeAndMessageEnum.DELETE_MANY_SUCCESS;
        }
        return CodeAndMessageEnum.ERROR_NOT_EXIST;
    }
}
